package com.oneinlet.server.handler

import com.oneinlet.Pandora
import com.oneinlet.server.ServerChannelManage
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufUtil
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import org.slf4j.LoggerFactory

/**
 * Created by WangZiHe on 2019/1/9/009
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */
class AppServerHandler : SimpleChannelInboundHandler<ByteBuf>() {

    private val logger = LoggerFactory.getLogger(this.javaClass)

    override fun channelActive(ctx: ChannelHandlerContext) {
        ServerChannelManage.addAppChannel(ctx.channel().id().asLongText(), ctx.channel())
        // 长连接需要发一个空包到服务器
        val pandora = Pandora()
        val channelId = ctx.channel().id().asLongText()
        pandora.channelId = channelId
        pandora.msgType = Pandora.MsgType.SEND_MSG_FROM_YCSERVER_TO_YCLINET.type
        pandora.data = ByteBufUtil.getBytes(Unpooled.EMPTY_BUFFER)
        ServerChannelManage.YClientChannel.writeAndFlush(pandora)
    }


    override fun channelRead0(ctx: ChannelHandlerContext, byteBuf: ByteBuf) {
        sendYClient(ctx, byteBuf)
    }


    override fun channelReadComplete(ctx: ChannelHandlerContext?) {

    }

    override fun channelInactive(ctx: ChannelHandlerContext) {
        ServerChannelManage.removeAppChannel(ctx.channel().id().asLongText())
    }

    private fun sendYClient(ctx: ChannelHandlerContext?, byteBuf: ByteBuf) {
        val pandora = Pandora()
        val channelId = ctx!!.channel().id().asLongText()
        pandora.channelId = channelId
        pandora.msgType = Pandora.MsgType.SEND_MSG_FROM_YCSERVER_TO_YCLINET.type
        pandora.data = ByteBufUtil.getBytes(byteBuf)
        ServerChannelManage.YClientChannel.writeAndFlush(pandora)
    }


    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        ServerChannelManage.removeAppChannel(ctx!!.channel().id().asLongText())
        logger.error("应用客户端通道异常关闭", cause)
    }
}
